import { _decorator, Component, instantiate, Node, Prefab, Sprite,find ,Animation} from 'cc';
import { GameMgr } from '../../src/GameMgr';
import { TankAI } from '../../src/Game/TankAI';
import { EventMgr } from '../../EventMgr/EventMgr';
import { Random } from '../../mathAlgo/Random';
import { DropProp } from '../../src/Game/DropProp';
import { ColorHp } from '../../src/Game/ColorHp';
const { ccclass, property } = _decorator;

@ccclass('TankCreate')
export class TankCreate extends Component {

    private tankPrefabs: Node[] = [];

    private createTimer:number=0;

    @property createCount:number=5;

     stopCreate:boolean=false;

    start() {
        this.tankPrefabs=find("Canvas/tmp").children.filter(n=>n.name.indexOf("enemy")>=0);
        this.node.getComponent(Sprite).enabled=false;

       // this.enabled=false;
       this.stopCreate=true;
        EventMgr.Inst.addEvent("GAME_START",this.onGameStart,this);
    }

    getCreateCount():number{
        return this.createCount;
    }

    onGameStart(){
       // console.log("i am tankcreate onstart");
        this.stopCreate=false;
       //this.enabled=true; 
    }
    protected onDestroy(): void {
         EventMgr.Inst.removeEvent("GAME_START",this.onGameStart,this);
    }

    flashStar(){
        this.node.children[0].active=true;

        this.node.children[0].getComponent(Animation).stop();
        this.node.children[0].getComponent(Animation).play();

        this.scheduleOnce(()=>{
            this.node.children[0].active=false;

        },0.5);

    }

    createEnemy(){
        //if(GameMgr.Inst.limitEnemyCount_continue()===false) return;

        if(this.createCount>0){
            this.flashStar();
            let n:Node =instantiate( Random.RandomItem( this.tankPrefabs));
            let {x,y}=this.node.getPosition();
            n.setPosition(x,y);
            find("Canvas/enemys").addChild(n);

            this.addCreatePropFunc(n);

            //console.log("createEnemy");
            this.createCount-=1;

        }
    }

    addCreatePropFunc(n:Node):void{
        if(Math.random()<0.35){
         n.addComponent(DropProp);
        }else {
            n.addComponent(ColorHp);
        }
    }

    update(deltaTime: number) {
        if(this.stopCreate)return;


        this.createTimer-=deltaTime;
        if(this.createTimer<0){
            this.createEnemy();

            this.createTimer=4;
        }

    }
}


